/*
 @Date: 2022/5/4
 @Desc: 照片编辑
 */

import UIKit

class IPEditPhotoViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    var chiCunStr = ""
    var selectImg = UIImage()
    
    @IBOutlet weak var heightC: NSLayoutConstraint!
    @IBOutlet weak var widthC: NSLayoutConstraint!
    
    @IBOutlet weak var biLic: NSLayoutConstraint!
    
    
    //MARK: 图片区
    @IBOutlet weak var iconIV: UIImageView!
    @IBOutlet weak var rightPxLabel: UILabel!
    @IBOutlet weak var bottomPxLabel: UILabel!
    @IBOutlet weak var leftPxLabel: UILabel!
    @IBOutlet weak var topPxLabel: UILabel!
    
    //MARK: 工具区
    @IBOutlet weak var toolsView: UIView!
    
    @IBOutlet weak var editLipColor: UIButton!
    @IBOutlet weak var editBeauty: UIButton!
    @IBOutlet weak var editBgBt: UIButton!
    
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var diSeView: UIView!
    @IBOutlet weak var collcetionView1: UICollectionView!
    let backColor = [UIColor.init(red: 47/255.0, green: 125/255.0, blue: 255/255.0, alpha: 1),UIColor.init(red: 255/255.0, green: 40/255.0, blue: 40/255.0, alpha: 1),UIColor.init(red: 113/255.0, green: 166/255.0, blue: 255/255.0, alpha: 1),UIColor.init(red: 193/255.0, green: 193/255.0, blue: 193/255.0, alpha: 1),UIColor.init(red: 31/255.0, green: 31/255.0, blue: 31/255.0, alpha: 1),UIColor.white,UIColor.init(red: 255/255.0, green: 236/255.0, blue: 234/255.0, alpha: 1)]
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
        self.topPxLabel.text = chiCunStr.components(separatedBy: "x").first! + "px"
        self.bottomPxLabel.text = chiCunStr.components(separatedBy: "x").first! + "px"
        self.leftPxLabel.text = chiCunStr.components(separatedBy: "x").last! + "px"
        self.rightPxLabel.text = chiCunStr.components(separatedBy: "x").last! + "px"
        let w = CGFloat((chiCunStr.components(separatedBy: "x").first! as NSString).floatValue)
        let h = CGFloat((chiCunStr.components(separatedBy: "x").last! as NSString).floatValue)
        let hi = (UIScreen.main.bounds.size.width - 44 - 30)*(383/330.0)
        
        //        if w > UIScreen.main.bounds.size.width - 44 - 30 {
        //            w = UIScreen.main.bounds.size.width - 44 - 30
        //        }
        //        if h > hi - 30 {
        //            h = UIScreen.main.bounds.size.width - 44 - 30
        //        }
        
        print(w/h*hi)
        self.widthC.constant = w/h*hi
        self.heightC.constant = hi
        //        biLic.constant = w / h
        self.iconIV.image = selectImg
        //        self.collcetionView1.register(UINib.init(nibName: "UICollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cellID1")
        self.collcetionView1.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID1")
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 39.0, height: 39.0)
        self.collcetionView1.collectionViewLayout = layout
        mainView.addSubview(diSeView)
        
        
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        //        self.iconIV.frame.size.width = 200
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 返回按钮
        let backButton = UIButton(type: .custom)
        // 给按钮设置返回箭头图片
        backButton.setBackgroundImage(#imageLiteral(resourceName: "backimg"), for: .normal)
        // 设置frame
        backButton.frame = CGRect(x: 0, y: 13, width: 11, height: 19)
        backButton.addTarget(self, action: #selector(back), for: .touchUpInside)
        // 自定义导航栏的UIBarButtonItem类型的按钮
        let backView = UIBarButtonItem(customView: backButton)
        // 返回按钮设置成功
        navigationItem.leftBarButtonItem = backView
        
        
        let saveButton = UIButton(type: .custom)
        //        saveButton.setBackgroundImage(#imageLiteral(resourceName: "backimg"), for: .normal)
        saveButton.setTitle("保存", for: .normal)
        saveButton.backgroundColor = UIColor.init(red: 77/255.0, green: 140/255.0, blue: 251/255.0, alpha: 1)
        saveButton.frame = CGRect(x: 0, y: 13, width: 45, height: 24)
        saveButton.addTarget(self, action: #selector(save), for: .touchUpInside)
        let saveView = UIBarButtonItem(customView: saveButton)
        navigationItem.rightBarButtonItem = saveView
        
        self.title = "照片编辑"
    }
    @objc func back() {
        self.navigationController?.popViewController(animated: true);
    }
    @objc func save() {
        if var list = UserDefaults.standard.object(forKey: "saveList")as? [Data] {
            let image = self.getViewScreenshot(view: self.iconIV)
            let data:Data = image.pngData()!
            list.append(data)
//            UserDefaults.setValue(list, forKey: "saveList")
            UserDefaults.standard.setValue(list, forKey: "saveList")
        }else{
            var list = [Data]()
            let image = self.getViewScreenshot(view: self.iconIV)
            let data:Data = image.pngData()!
            list.append(data)
            UserDefaults.standard.setValue(list, forKey: "saveList")
        }
        
    }
    @objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        
        print("Save finished!")
        
    }
    func getViewScreenshot(view: UIView) -> UIImage {
        let w = CGFloat((chiCunStr.components(separatedBy: "x").first! as NSString).floatValue)
        let h = CGFloat((chiCunStr.components(separatedBy: "x").last! as NSString).floatValue)
//        var V = UIView.init(frame: CGRect(x: 0, y: 0, width: w, height: h))
        let size = CGSize(width: w, height: h)
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, UIScreen.main.scale)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    //MARK: 工具类点击事件
    @IBAction func didClickEditImageBackground(_ sender: UIButton) {
        sender.isSelected = true
        //        editBeauty.isSelected = false
        //        editLipColor.isSelected = false
    }
    
    @IBAction func didClickEditImageBeauty(_ sender: UIButton) {
        sender.isSelected = true
        editLipColor.isSelected = false
        editBgBt.isSelected = false
    }
    
    @IBAction func didClickEditImageLipColor(_ sender: UIButton) {
        sender.isSelected = true
        editBeauty.isSelected = false
        editBgBt.isSelected = false
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return backColor.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID1", for: indexPath)
        if collectionView == collcetionView1 {
            cell.layer.cornerRadius = 5
            cell.backgroundColor = backColor[indexPath.item]
        } else {
            
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        [JiaMiObject .post("https://bda.tencentcloudapi.com", params: ["Image":self.imageToBase64(image: selectImg)], success: { result in
            print(result)
            let Response = result["Response"]as! NSDictionary
            let ResultImage = Response["ResultImage"]
            DispatchQueue.main.async {
                self.iconIV.image = self.convertStrToImage(ResultImage as! String)
                self.iconIV.backgroundColor = self.backColor[indexPath.item]
            }
            
        }, failure: { error in
            print(error)
        })];
    }
    func convertStrToImage(_ imageStr:String) ->UIImage?{
        if let data: NSData = NSData(base64Encoded: imageStr, options:NSData.Base64DecodingOptions.ignoreUnknownCharacters)
        {
            if let image: UIImage = UIImage(data: data as Data)
            {
                return image
            }
        }
        return nil
    }
    func imageToBase64(image: UIImage) -> String {
        //将获取的图片通过jpegData(compressionQuality: 1.0)方法转成Data类型的数据。
        //参数1.0表示不压缩，因为jpeg是有损格式，jpg和jpeg都用这个方法。无损格式PNG使用pngData()方法转换，没有参数，也就是不压缩。
        let imageData: Data? = image.jpegData(compressionQuality: 1.0)
        let str: String = imageData!.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
        //返回
        return str
    }
    
}

//MARK: 一些ui的基本设置
private extension IPEditPhotoViewController {
    
    func setupUI() {
        setupToolsView()
    }
    
    func setupToolsView() {
        toolsView.layer.borderColor = UIColor.ip_cell_border_color.cgColor
    }
}

//MARK: 一些数据的订阅
private extension IPEditPhotoViewController {
    
    func setupData() {
        
    }
}
